<?php
/**
 * Section Creation/Update Popup
 * 
 * @author	Xavier VILAIN
 * @package Nawa\Survey
 * @license #license-nawa-surver#
 * 
 */

use Fox\Html\Block;
use Nawa\Survey;
use Nawa\Survey\Section;
use Nawa\Messages;
use Fox\Popup;
use Fox\Html\TextArea;
use Fox\Html\Input;
use Fox\Html\Screen;

$xview = Xview::instance();
$keys = $xview->val(array('surveyid','sectionid'));
// Load Survey
$survey = $xview->component('survey','object');

if(!empty($keys['sectionid'])) {
	$mode = 'update';
	$label = Msg(Messages::BUNDLE,Messages::SURVEY_SECTION_UPDATE_TITLE);
	$section = $survey->findSections($keys['surveyid'].':'.$keys['sectionid']);
} else {
	$mode = 'create';
	$label = Msg(Messages::BUNDLE,Messages::SURVEY_ADD_SECTION);
	$section = new Section();
}
$data = $section->getData();
$screen = new Screen('mSection',$mode,null,true,Fox\Generator::ajaxReload('MC_sections'));
$screen
	->block()
		->add(new Input(array('section_label','label'),true));
$block = new Block('bSectionText',Msg(Fox\Msg::BUNDLE,Fox\Msg::TITLE_TEXT_DATA));
$block->collapsed(true)
		->add(new TextArea(array('section_description','description')))->parentObject()
		->add(new TextArea(array('section_introduction','introduction')))->parentObject()
		->add(new TextArea(array('section_conclusion','conclusion')))->parentObject()
	;
$screen->add($block);
$screen->initialize($data);

if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		
		try {
			$section->setFields($fields);
			if($section->exists()) {
				$section->update();
				Fox\Message::Success(Msg(Messages::BUNDLE,
									Messages::SURVEY_SECTION_HAS_BEEN_UPDATED,
									$section->label()));
			} else {
				$position =10;
				$section->language = $survey->language;
				// At the section at the bottom of the list
				foreach($survey->sections() as $currentSection) {
					if($position <= $currentSection->position) {
						$position = $currentSection->position;
					}
				}
				$position += 10;
				$section->position = $position;
				$survey->addToSections($section);
				
				$survey->prepareUpdate(Survey::CHANGE_ADD_SECTION);
				$survey->update();
				Fox\Message::Success(Msg(Messages::BUNDLE,
									Messages::SURVEY_SECTION_HAS_BEEN_CREATED,
									$section->label()));
			}
			echo $xview->messages(true,true);
			exit;
		} catch (Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
		echo $xview->messages(true,false);
		exit;
	}
}
$popup = new Popup('pSections',$label,$screen,600);
echo $popup->display();